package com.maychat.websocket;

import com.alibaba.fastjson2.JSON;
import com.maychat.pojo.extended.Message;
import com.maychat.utils.StringTools;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MessageHandler {

    public static final String MESSAGE_TOPIC = "message.topic";

    @Resource
    private RedissonClient redissonClient;

    @Autowired
    private ChannelContextUtils channelContextUtils;

    @PostConstruct
    public void listMsg() {
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.addListener(Message.class, (str, msg) -> channelContextUtils.sendMsg(msg));
    }

    public void sendMsg(Message<?> msg) {
        log.info("发送消息：{}", StringTools.stringify(msg));
        RTopic rTopic = redissonClient.getTopic(MESSAGE_TOPIC);
        rTopic.publish(msg);
    }
}
